const uniID = require('uni-id-common')

/**
 * 校验 token
 */
module.exports = async function validateToken() {
  const { body = {} } = this.getHttpInfo()
  const { uniIdToken } = JSON.parse(body).clientInfo
  const clientInfo = this.getClientInfo()

  this.uniIdToken = uniIdToken

  if (!uniIdToken) {
    throw { errCode: 400, errMsg: 'token不存在' }
  }

  // 多次执行validateToken时如果第一次成功后续不再执行
  if (this.authInfo) {
    return
  }

  this.uniIDIns = uniID.createInstance({ clientInfo })
  const authInfo = await this.uniIDIns.checkToken(uniIdToken, {
    autoRefresh: false
  })

  // token 有问题
  if (authInfo.errCode !== 0) {
    const mapper = {
      'uni-id-check-token-failed': 'token校验错误',
      'uni-id-token-expired': '登录过期，请重新登录'
    }

    if (mapper[authInfo.errCode]) {
      throw { errCode: 400, errMsg: mapper[authInfo.errCode] }
    }

    throw { errCode: 400, errMsg: 'token有误，请联系管理员' }
  }

  /**
   * token 没问题，挂载权限信息
   * authInfo
   * 	exp: 1741669004
   * 	iat: 1741661804
   * 	permission: []
   * 	role: ["admin"]
   * 	uid: "6795cc099755e3746282d1d1"
   */
  this.authInfo = authInfo
}
